package cn.flkj.evidence.RocketMQConsumer.Utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class OperationTxt {

    private File file;
    protected final static Logger logger  = LoggerFactory.getLogger(OperationTxt.class);

    public OperationTxt(String filename) {
        file = new File(System.getProperty("user.dir")+"/config/"+filename);
    }

    public boolean isEmpty() {
        return (readTxtContent() == null || readTxtContent().isEmpty());
    }

    public String setContent(String content) {
        writeTxtContent(content);
        return content;
    }

    public String getContent() {
        if (isEmpty()) {
            return "{}";
        }
        return readTxtContent();
    }

    private String readTxtContent() {
        String lineTxt = null;
        try {
            String encoding = "UTF-8";
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                lineTxt = bufferedReader.readLine();
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错\n"+e);
        }
        return lineTxt;
    }

    private void writeTxtContent(String content) {
        FileWriter fw;
        try {
            fw = new FileWriter(file);
            fw.write(content);
            fw.flush();
            fw.close();
        } catch (IOException e) {
            logger.error("写入文件失败 { " + e + " } " );
        }
    }
}